
$(function() {

	var menu;
	var actionNodeID;
	 var availableTags = [];
	 var getEmps = function() {
	 	$.ajax({
	 		url: '/api/employee/all?_t=' + new Date().getTime(),
	 		type: 'get',
	 		success: function(data) {
	 			// console.info(data);
	 			if(data != "none") {
	 				for(var i = 0; i < data.length; i ++) {
	 					// console.info(data[i].id);
	 					var showStr = data[i].name + "-" + data[i].orgAddress + "-" + data[i].orgName;
	 					var item = {
	 						label: showStr,
	 						value: data[i].name,
	 						empId: data[i].id
	 					}
	 					availableTags.push(item);
	 				}
	 			}
	 		}
	 	});
	 };

	 getEmps();

	$("#orgresp").autocomplete({
	      source: availableTags,
	      select: function( event, ui ) {
	        $("#respId").val(ui.item.empId);
	        $("#hideName").val(ui.item.value);
	      },
	 });

	//添加机构
	$("#addBtn").click(function(){
		// $("#message").css('display','none');
		// $("#typeMsg").css("display","none");
		// $("#showOrgsystem").css("display","none");
		// $("#showAddress").css("display","none");
		hideMessage();
		$("#parent").val("");
		$("#orgname").val("");
		$("#parentShow").val("");
		$("#orgresp").val("");
		$("#respId").val("");
		$("#hideName").val("");

		
		initSys();
		$("#orgsystem").html("<option  value='-1'>--- 选择体系 ---</option>");
		$("#orgtype").get(0).options[0].selected = true;
		$("#orgAdd").modal('show');
	});

	//根据机构类型动态显示机构所属体系及机构所属区域
	$("#orgtype").change(function(){
		var typeValue = $("#orgtype option:selected").val();
		if(typeValue == "C") {
			$("#showOrgsystem").css("display","none");
			$("#showAddress").css("display","block");
		}else if(typeValue == "D") {
			$("#showOrgsystem").css("display","block");
			$("#showAddress").css("display","none");

		}
	});
	//初始化体系下拉框
	var initSys = function() {
		// alert(orgType);
		$.ajax({
			url: '/api/system?_t='+ new Date().getTime(),
			type: 'get',
			success: function(data) {
				 // console.info('hehe',data);
				if(data != null && data.length != 0) {
					$.each(data, function(i, sys) {
						$("#orgsystem").append("<option value='" + sys.id + "'>" + sys.sysName + "</option>");
					});
				}
			}
		});
		
	};

	//选择上级机构
	$("#parentOrg").click(function() {
		$("#chooseOrg").html("");
		$("#orgAdd").modal('hide');
		$("#chooseParent").modal('show');
		$("#chooseOrg").ligerTree(
		          {   
		              url: '/api/organizations/getOrgTree?_t=' + new Date().getTime(), 
		              method: 'get',
		              checkbox: false,
		              nodeWidth: 120,
		              idFieldName: "id",
		              parentIDFieldName: 'pid',
		              slide: false,
		              onSelect: function(node) {
		              	actionNodeID = node.data.id;
		              	// alert(actionNodeID);
		              	$.ajax({
		              		url: '/api/organizations/getParents/' + actionNodeID ,
		              		type: 'get',
		              		success: function(result) {		          
		              			
		              			var parentString = "";
		              			for(var i = result.length-1; i >= 0; i--){
		              				if(i != 0) {
		              					if(result[i].orgName == "分公司") {
		              						continue;
		              					}else{
		              						parentString += result[i].orgName + "/";
		              					}
		              					
		              				}else{
		              					parentString += result[i].orgName;
		              				}
		              			}
		              			
		              			$("#parentShow").val(parentString);
		              			
		              			$("#parent").val(result[0].id);
		              			$("#hideAddress").val(result[0].orgAddress);
		              			$("#orgAdd").modal('show');
		              			$("#chooseParent").modal('hide');

		              		}
		              	});

		              }
		          });

	});

	$("#cancle").click(function() {
		$("#orgAdd").modal('show');
	});

	$("#cancleSave").click(function() {
		// alert("release");
		// $("#message").css('display','none');
		// $("#typeMsg").css("display","none");
		// $("#showOrgsystem").css("display","none");
		// $("#showAddress").css("display","none");
		hideMessage();
		$("#orgname").val("");
		$("#parentShow").val("");
		$("#orgresp").val("");
		$("#respId").val("");
		$("#hideName").val("");
		$("#respMsg").css("display","none");
		
		$("#orgsystem").html("<option  value='-1'>--- 选择体系 ---</option>");
		$("#orgtype").get(0).options[0].selected = true;

		
	});

	//点击保存按钮
	$("#saveOrg").click(function() {

		var orgModel = buildModel();
		// console.info(orgModel);
		// return;
		if(orgModel.orgName == "") {
			$("#message").html("请填写机构名称");
			$("#message").css('display','block');
			return;
		}
		if(orgModel.orgType == "") {
			$("#typeMsg").html("请选择机构类型");
			$("#typeMsg").css('display','block');
			return;
		}
		if(orgModel.orgType == "C" && orgModel.orgAddress == "") {
			$("#addrMsg").html("请选择机构所属区域");
			$("#addrMsg").css('display','block');
			return;
		}
		//如果机构的父机构id为-1，则判断是否已存在根节点
		if(orgModel.parentId == -1) {
			$.ajax({
				url: '/api/organizations/checkRoot?_t=' + new Date().getTime(),
				type: 'get',
				success: function(result) {
					// console.info("lijuanxia", result);
					if(result != null && result.length != 0) {
						// alert("111");
						$("#parentMsg").css("display", "block");
						return;
					}
				}
			});
		}
		
		var type;
		//判断是新增机构还是更新机构
		if(orgModel.id == null || orgModel.id == "") {
			type = "post";
		}else{
			type = "put";
		}

		$.ajax({
			url: '/api/organizations/checkOrgName?',
			type: 'get',
			data: {'orgData':JSON.stringify(orgModel), 'type':type, '_t': new Date().getTime()},
			success: function(result) {
				// alert(result);
				
				var status = $("#message").css("display");
				// $("#typeMsg").css("display","none");
				// $("#showOrgsystem").css("display","none");
				// $("#showAddress").css("display","none");
				hideMessage();
				//result为true机构名称没有重复
				if(result == "true"){
					if(status == "block") {
						$("#message").toggle();
					}
					saveOrgData(orgModel, type);
					
				}else{
					if(status == "none") {
						$("#message").html("机构名称重复");
						$("#message").toggle();
					}else{
						$("#message").html("机构名称重复");
					}
					
					return;
				}

			}
		});

	});

	//提交后台保存机构
	var saveOrgData = function(orgModel, type) {
		// console.info("saveOrgData");
	
		var newData = {};
		if(type == "post") {
			newData.orgName = orgModel.orgName;
			newData.parentId = orgModel.parentId;
			newData.systemId = orgModel.systemId;
			newData.orgType = orgModel.orgType;
			newData.orgManager = orgModel.orgManager;
			newData.orgAddress = orgModel.orgAddress;
		}else{
			newData = orgModel;
		}
		// console.info("-----newData---------");
		// console.info(newData);
		// return;
		$.ajax({
			url: '/api/organization',
			type: type,
			data: newData,
			success: function(result) {
				// alert(result);
				if(result == 'noPrivilege'){
					bootbox.alert('您没有权限,操作失败！');
					return;
				}
				bootbox.alert(result);

				$("#orgAdd").modal('hide');
				
				showTree();
				// window.location.reload();

			}
		});
	};
	//机构负责人输入框光标移开事件
	$("#orgresp").blur(function(){
		var respName = $("#orgresp").val().replace(/(^\s*)|(\s*$)/g, "");
		var respId = $("#respId").val();
		var hideName = $("#hideName").val();
		if(respName == "") {
			$("#respId").val("");
			$("#hideName").val("");
		}else{
			$.ajax({
				url: '/api/employee/getEmpByName?',
				type: 'get',
				data: {'empName':respName, '_t':new Date().getTime()},
				success: function(result) {
					// console.info("org---result:", result);
					if(result != null && result.length != 0) {
						// alert(respId);
						if(respId == null || respId == "" || respId == 0) {
							$("#respId").val(result[0].id);
						}else if(result[0].name != hideName) {
							$("#respId").val(result[0].id);
						}
					}else{
						$("#respMsg").html("员工不存在！");
						$("#respMsg").css("display","block");
					}
				}
			});
		}
	}); 

	//获取页面数据并构建机构模型
	var buildModel = function(){
		var $orgid = $("#orgid").val();
		var $orgname = $("#orgname").val();
		var $parent = $("#parent").val() == "" ? -1 : $("#parent").val();
		var $orgManager = $("#respId").val();
		// var $orgsystem = $("#orgsystem").val();
		var $orgsystem = $("#orgsystem option:selected").val() == -1 ? "" : $("#orgsystem option:selected").val();
		var $orgtype = $("#orgtype option:selected").val() == -1 ? "" : $("#orgtype option:selected").val(); 


		var model = {};
		model.id = $orgid;
		model.orgName = $orgname;
		model.parentId = $parent;
		model.systemId = $orgsystem;
		model.orgType = $orgtype;
		model.orgManager = $orgManager;
		// model.orgAddress = $orgAddress;
		if(model.orgType == "C") {
			model.orgAddress = $("#orgAddress option:selected").val() == -1 ? "" : $("#orgAddress option:selected").text(); 
		}else{
			model.orgAddress = $("#hideAddress").val()
		}
		
		

		return model;
	};


    //树形节点右键点击菜单事件
	var itemclick = function(item, i) {
		$("#respMsg").css("display","none");
		// alert(actionNodeID + " | " + item.text);
		if(item.text == "增加") {
			$("#orgsystem").html("<option  value='-1'>--- 选择体系 ---</option>");
			$("#orgtype").get(0).options[0].selected = true;

			initSys();
			$("#title").html("添加机构");
			// console.info("actionNodeID = " + actionNodeID);
			$("#orgid").val("");
			$.ajax({
				url: '/api/organizations/getParents/' + actionNodeID ,
				type: 'get',
				success: function(result) {
					
					var parentString = "";
					// alert(result.length);
					for(var i = result.length-1; i >= 0; i--){
						if(i != 0) {
							if(result[i].orgName == "分公司") {
								continue;
							}else{
								parentString += result[i].orgName + "/";
							}
							
						}else{
							parentString += result[i].orgName;
						}
					}
					
					$("#parentShow").val(parentString);
					
					$("#parent").val(result[0].id);
					$("#hideAddress").val(result[0].orgAddress);
					// console.info(result[0]);
					// console.info($("#parent").val());

				}
			});
			$("#orgAdd").modal('show');
		}else if(item.text == "修改") {
			$("#orgsystem").html("<option  value='-1'>--- 选择体系 ---</option>");
			$("#orgtype").get(0).options[0].selected = true;
			initSys();
			$("#title").html("编辑机构");
			$("#orgid").val(actionNodeID);
			$("#orgAdd").modal('show');
			$.ajax({
				url: '/api/organizations/selOrg/' + actionNodeID,
				type: 'get',
				success: function(result) {
					// console.info(result);
					var org = result.orgData;
					var parents = result.parentData;
					// $("#hideAddress").val(result[0].orgAddress);

					var parentString = "";
					// alert(parents.length);
					for(var i = parents.length-1; i >0; i--){
						if(i != 1) {
							if(parents[i].orgName == "分公司") {
								continue;
							}else{
								parentString += parents[i].orgName + "/";
							}
							
						}else{
							parentString += parents[i].orgName;
						}
					}
					// console.info(parentString);
					if(parents.length > 1) {
						
						$("#parentbtn").css('display', 'block');

						$("#parentShow").val(parentString);
						
						$("#parent").val(parents[1].id);
						$("#hideAddress").val(parents[1].orgAddress);
					}else{
						$("#parentbtn").css('display', 'none');

						$("#parentShow").val("根节点");
						
						$("#parent").val(-1);
						$("#hideAddress").val("北京");
					}
					

					$("#orgid").val(org.id);
					$("#orgname").val(org.orgName);
					$("#orgresp").val(org.empName);
					$("#hideName").val(org.empName);
					$("#respId").val(org.orgManager);
					// $("#orgsystem").val(org.orgSystem);

					// initSys(org.orgType); //下拉菜单的初始化不能放在ajax里
					if(org.orgType == "C") {
						$("#showOrgsystem").css("display","none");
						$("#showAddress").css("display","block");
					}else if(org.orgType == "D") {
						$("#showOrgsystem").css("display","block");
						$("#showAddress").css("display","none");
					}
					
					for(var i = 0 ; i < $("#orgsystem option").length; i++) {
						// alert($("#orgsystem").get(0).options[i].value);
						if($("#orgsystem").get(0).options[i].value == org.systemId) {
							$("#orgsystem").get(0).options[i].selected = true;
						}
					}
					for(var i = 0 ; i < $("#orgtype option").length; i++) {
						if($("#orgtype").get(0).options[i].value == org.orgType) {
							$("#orgtype").get(0).options[i].selected = true;
						}
					}
					for(var i = 0 ; i < $("#orgAddress option").length; i++) {
						if($("#orgAddress").get(0).options[i].text == org.orgAddress) {
							$("#orgAddress").get(0).options[i].selected = true;
						}
					}

					
				}
			});

		}else if(item.text == "删除"){
			//删除 机构下没有子机构并且没有员工属于这个机构时才能删除机构
			bootbox.confirm("确定删除该机构？", function(result) {
				if(result) {
					$.ajax({
						url: '/api/organizations/orgCheck/' + actionNodeID,
						type: 'get',
						success: function(result) {
							//result的值为true表示该机构可以删除
							// alert(result);
							if(result == "true") {
								deleteOrg(actionNodeID);
							}else if(result == "hasChild") {
								bootbox.alert("机构下存在子机构，不能删除！");
							}else{
								bootbox.alert("机构下存在员工，不能删除！");
							}
							
						}
					});
				}
			});
			

		}else if(item.text == "查看成员") {
			var nw=window.open("about:blank","");
			nw.location="/organization/orgEmp?orgId=" + actionNodeID;

		}
	};
	var deleteOrg = function(orgid) {
		$.ajax({
			url: '/api/organization?orgId=' + orgid,
			type: 'DELETE',
			success: function(result) {
				if(result == 'noPrivilege'){
					bootbox.alert('您没有权限,操作失败！');
					return;
				}
				bootbox.alert("删除机构成功");
				showTree();
			},
			error: function(result) {
				bootbox.alert("删除机构失败");
			}
		});
	};
	
	
	var showTree = function() {
		$("#tree1").html("");
		// $("#message").css('display','none');
		// $("#parentMsg").css('display', 'none');
		// $("#typeMsg").css("display","none");
		// $("#showOrgsystem").css("display","none");
		// $("#showAddress").css("display","none");
		$("#parentMsg").css('display', 'none');
		$("#orgname").val("");
		$("#parentShow").val("");
		$("#orgresp").val("");
		$("#respId").val("");
		$("#hideName").val("");

        menu = $.ligerMenu({ top: 100, left: 100, width: 120, items:
                  [
                  { text: '增加', click: itemclick, icon: 'add' },
                  { text: '修改', click: itemclick },
                  { text: '删除', click: itemclick},
                  { line: true },
                  { text: '查看成员', click: itemclick}
                  ]
                  });

		$("#tree1").ligerTree(
		          {   
		              url: '/api/organizations/getOrgTree?_t=' + new Date().getTime(), 
		              // data:[{"id":1,"text":"系统管理","url":"#","pid":null},{"id":2,"text":"菜单管理","url":"#","pid":1}], 
		              method: 'get',
		              checkbox: false,
		              nodeWidth: 120,
		              idFieldName: "id",
		              parentIDFieldName: 'pid',
		              // single: true,
		              slide: false,
		              onContextmenu: function (node, e)
		                          { 
		                              actionNodeID = node.data.id;
		                              menu.show({ top: e.pageY, left: e.pageX });
		                              return false;
		                          },
		              //点击查看机构
		              onSelect: function(node) {
		              	actionNodeID = node.data.id;
		              	$.ajax({
		              		url: '/api/organizations/selOrg/' + actionNodeID,
		              		type: 'get',
		              		success: function(result) {
		              			// console.info(result);
		              			$("#selOrg").modal('show');
		              			var org = result.orgData;
		              			var parents = result.parentData;

		              			var parentString = "";
		              			for(var i = parents.length-1; i > 0; i--){
		              				if(i != 1) {
		              					if(parents[i].orgName == "分公司") {
		              						continue;
		              					}else{
		              						parentString += parents[i].orgName + "/";
		              					}
		              					// parentString += parents[i].orgName + "/";
		              				}else{
		              					parentString += parents[i].orgName;
		              				}
		              			}
		              			// console.info(parentString);
		              			if(parents.length > 1) {
		              				
		              				$("#showParent").html(parentString);		            
		              			}else{
		              			
		              				$("#showParent").html("根节点");
		              				
		              			}
		              			if(org.orgType == "C") {
		              				$("#changeMsg").html("所属区域：");
                                    $("#showSys").html(org.orgAddress);
		              			}else if(org.orgType == "D"){
		              				$("#changeMsg").html("所属体系：");
                                    $("#showSys").html(org.sysName);
		              			}
		              		
		              			$("#orgid").html(org.id);
		              			$("#showName").html(org.orgName);
		              			// $("#showSys").html(org.sysName);
		              			$("#orgResp").html(org.empName);
		              			$("#showAddr").html(org.orgAddress);
		              			
		              			
		              			
		              		}
		              	});
		              }
		              		              	
		          });

		      };

	showTree();	

	var hideMessage = function() {
		$("#typeMsg").css("display","none");
		$("#showOrgsystem").css("display","none");
		$("#showAddress").css("display","none");
		$("#message").css('display','none');
		$("#parentMsg").css('display', 'none');
		$("hideAddress").val("");
		$("#respMsg").css("display","none");
	};


});